import * as echarts from '../../components/ec-canvas/echarts'
const api = require('../../utils/api')

Page({
    data: {
        ec: { lazyLoad: true }
    },

    onLoad() {
        // 创建图表实例（延迟加载）
        this.ecComponent = this.selectComponent('#sexChart');
    },

    onShow() {
        this.getChartData();
    },

    generateOption(data) {
        const legendData = [];
            const chartData = [];
            for (const item of data) {
                legendData.push(item.sexName);
                chartData.push({
                    name: item.sexName,
                    value: item.count
                });
            }

        // 饼图配置
        return {
            title: {
                text: '性别分布',
                left: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: '{a} \n{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'horizontal',
                bottom: 0,
                data: legendData
            },
            series: [
                {
                    name: '人数',
                    type: 'pie',
                    radius: '60%',
                    data: chartData,
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0,0,0,0.5)'
                        }
                    }
                }
            ]
        };
    },

    initChart(option) {
        // 初始化图表
        this.ecComponent.init((canvas, width, height, dpr) => {
            let chart = this.chart;

            if (!chart) {
                // 首次初始化
                chart = echarts.init(canvas, null, {
                    width: width,
                    height: height,
                    devicePixelRatio: dpr
                });
                canvas.setChart(chart);
                this.chart = chart;
            } else {
                // 更新：清空旧数据
                chart.clear();
                chart.resize({ width, height });
            }
            chart.setOption(option);
            return chart;
        });
    },

    getChartData() {
        api.getSexCharData().then(res => {
            if (!res.data.code || res.data.code !== 1) {
                wx.showToast({
                    title: res.data.msg,
                    icon: "error"
                });
                return;
            };
            const option = this.generateOption(res.data.data);
            this.initChart(option);
        })
    }
})